package edu.neu.ecommerceplatform.service.Impl;

import edu.neu.ecommerceplatform.Exception.ResourceNotFoundException;
import edu.neu.ecommerceplatform.dto.AddCartItemRequest;
import edu.neu.ecommerceplatform.dto.CartItemDetailDto;
import edu.neu.ecommerceplatform.dto.CartResponse;
import edu.neu.ecommerceplatform.dto.UpdateCartItemRequest;
import edu.neu.ecommerceplatform.mapper.CartItemMapper;
import edu.neu.ecommerceplatform.model.CartItem;
import edu.neu.ecommerceplatform.model.Product;
import edu.neu.ecommerceplatform.service.CartService;
import edu.neu.ecommerceplatform.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    private static final Logger logger = LoggerFactory.getLogger(CartServiceImpl.class);
    private final CartItemMapper cartItemMapper;
    private final ProductService productService;

    @Autowired
    public CartServiceImpl(CartItemMapper cartItemMapper, ProductService productService) {
        this.cartItemMapper = cartItemMapper;
        this.productService = productService;
    }

    @Override
    public CartResponse getCart(Integer userId) {
        logger.info("正在为用户ID获取购物车: {}", userId);
        List<CartItem> cartItems = cartItemMapper.findByUserId(userId);
        List<CartItemDetailDto> detailDtos = cartItems.stream()
                .map(this::mapToDetailDto)
                .collect(Collectors.toList());

        BigDecimal totalAmount = detailDtos.stream()
                .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        logger.info("成功为用户ID获取购物车: {}, 购物车中有 {} 件商品", userId, detailDtos.size());
        return new CartResponse(detailDtos, totalAmount);
    }

    @Transactional
    @Override
    public CartResponse addItemToCart(Integer userId, AddCartItemRequest request) {
        logger.info("用户ID {} 正在添加商品ID {} 到购物车, 数量: {}", userId, request.getProductId(), request.getQuantity());
        // Check if product exists
        productService.getProductById(request.getProductId());

        CartItem existingItem = cartItemMapper.findByUserIdAndProductId(userId, request.getProductId());
        if (existingItem != null) {
            logger.info("商品已存在于购物车中，正在更新数量。用户ID: {}, 商品ID: {}", userId, request.getProductId());
            existingItem.setQuantity(existingItem.getQuantity() + request.getQuantity());
            cartItemMapper.update(existingItem);
        } else {
            logger.info("商品为新商品，正在添加到购物车。用户ID: {}, 商品ID: {}", userId, request.getProductId());
            CartItem newItem = new CartItem(userId, request.getProductId(), request.getQuantity());
            cartItemMapper.save(newItem);
        }
        logger.info("成功为用户ID {} 添加商品到购物车", userId);
        return getCart(userId);
    }

    @Transactional
    @Override
    public CartResponse updateItemInCart(Integer userId, Integer productId, UpdateCartItemRequest request) {
        logger.info("用户ID {} 正在更新购物车中商品ID {} 的数量为: {}", userId, productId, request.getQuantity());
        CartItem existingItem = cartItemMapper.findByUserIdAndProductId(userId, productId);
        if (existingItem == null) {
            logger.warn("未在用户ID {} 的购物车中找到商品ID {}", userId, productId);
            throw new ResourceNotFoundException("CartItem", "productId", productId);
        }
        existingItem.setQuantity(request.getQuantity());
        cartItemMapper.update(existingItem);
        logger.info("成功为用户ID {} 更新了商品ID {} 的数量", userId, productId);
        return getCart(userId);
    }

    @Transactional
    @Override
    public CartResponse removeItemFromCart(Integer userId, Integer productId) {
        logger.info("用户ID {} 正在从购物车中移除商品ID {}", userId, productId);
        cartItemMapper.deleteByUserIdAndProductId(userId, productId);
        logger.info("成功从用户ID {} 的购物车中移除了商品ID {}", userId, productId);
        return getCart(userId);
    }

    @Transactional
    @Override
    public void clearCart(Integer userId) {
        logger.info("正在清空用户ID {} 的购物车", userId);
        cartItemMapper.deleteByUserId(userId);
        logger.info("成功清空用户ID {} 的购物车", userId);
    }

    private CartItemDetailDto mapToDetailDto(CartItem cartItem) {
        Product product = productService.getProductById(cartItem.getProductId());
        CartItemDetailDto dto = new CartItemDetailDto();
        dto.setProductId(product.getId());
        dto.setProductName(product.getName());
        dto.setImageUrl(product.getImageUrl());
        dto.setPrice(product.getPrice());
        dto.setQuantity(cartItem.getQuantity());
        return dto;
    }
} 